'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {
  // 登录 / 注册
  async login () {
    const { ctx, service, app } = this
    const payload = ctx.request.body || {}
    // console.log('payload', payload)
    const res = await service.user.login(payload)
    if (res) {
      const token = app.jwt.sign({
        'mobile': payload.mobile, //需要存储的 token 数据
      }, app.config.jwt.secret, { expiresIn: '2h' }); // 2小时token过期
  
      ctx.set({ 'token': token })//设置headers
  
      ctx.body = {
        code: '200',
        data: {
          token: token,
          ...res
        },
        message: 'success'
      };
    }
    // this.ctx.body = res
  }

  async loginToken () {
    const { ctx, service, app } = this
    const payload = ctx.request.body || {}
    const token = app.jwt.sign({
      'mobile': payload.mobile // 需要存储的 token 数据
    }, app.config.jwt.secret)
    console.log('token', token)
    ctx.set({'authorization': token}) // 设置 headers
    console.log('payload', payload)
    // const res = await service.user.login(payload)
    console.log(res)
    this.ctx.body = token
  }

  async findUserByToken () {
    const { ctx, service, app } = this
    // const token = ctx.request.body || {}
    const token = ctx.request.header.authorization
    console.log('token', token)
    // const find = function () {
    //   if (token === 'admin-token') {
    //     return users[token]
    //   }
    //   return users[token]
    // }
    // let res = find(token)
    try {
      const decode = await app.jwt.verify(token, app.config.jwt.secret);
      // console.log('decode', decode)
      const res = await service.user.getUser({mobile: decode.mobile})
      this.ctx.body = res
    } catch (err) {
      this.ctx.body = {msg: 'token已过期'}
    }
  }
  // 修改信息
  async update () {
    const { ctx, service } = this
    const payload = ctx.request.body || {}
    // console.log('payload', payload)
    const res = await service.user.update(payload)
    this.ctx.body = res
  }
  // 删除
  async deleteUser () {
    const { ctx, service } = this
    const payload = ctx.request.body || {}
    // console.log('payload', payload)
    const res = await service.user.deleteUser(payload)
    this.ctx.body = res
  }
  // 获取全部用户
  async getUser () {
    const { ctx, service } = this
    const params = ctx.query
    console.log('params', params)
    const res = await service.user.getUser(params)
    this.ctx.body = res
  }
  // 模糊搜索用户
  async getUsermohu () {
    const { ctx, service } = this
    const params = ctx.query
    console.log('params', params)
    const res = await service.user.getUsermohu(params)
    this.ctx.body = res
  }
  // 分页获取用户
  async getUserPaging () {
    const { ctx, service } = this
    const params = ctx.query
    const res = await service.user.getUserPaging(params)
    this.ctx.body = res
  }
}

module.exports = UserController;
